﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace Chefbook.HelperMethods
{
    /// <summary>
    /// Static helper class for validating parameters
    /// </summary>
    public static class ParameterValidation
    {
        /// <summary>
        /// Throws an ArgumentNullException if this is null, otherwise returns it
        /// </summary>
        /// <param name="valueToCheck">The object to check for null</param>
        /// <param name="parameterName">The name of the paramter being checked</param>
        /// 
        public static T ThrowIfNull<T>(this T valueToCheck, string parameterName)
        {
            if (valueToCheck == null)
            {
                throw new ArgumentNullException(parameterName);
            }
            return valueToCheck;
        }

        /// <summary>
        /// Throws an InvalidOperationException if this is false, otherwise returns it
        /// </summary>
        /// <param name="valueToCheck">The object to check for false</param>
        /// <param name="message">The error message to give</param>
        /// 
        public static bool ThrowIfFalse(this bool valueToCheck, string message)
        {
            if (valueToCheck == false)
            {
                throw new InvalidOperationException(message);
            }
            return valueToCheck;
        }

        /// <summary>
        /// Throws an ArgumentException if the assertion function does not hold true
        /// </summary>
        /// <param name="assertion">Function that returns true if argument is valid, otherwise false</param>
        /// <param name="parameterName">The name of the argument being checked</param>
        public static void ValidateArgument(Func<bool> assertion, string parameterName)
        {
            if (!assertion())
                throw new ArgumentException("Parameter {0} was invalid", parameterName);
        }

        /// <summary>
        /// Throws an ArgumentException if the assertion function does not hold true
        /// </summary>
        /// <param name="assertion">Function that returns true if argument is valid, otherwise false</param>
        /// <param name="parameterName">The name of the argument being checked</param>
        /// <param name="message">The message to dispay if validation fails</param>
        public static void ValidateArgument(Func<bool> assertion, string parameterName, string message)
        {
            if (!assertion())
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,"Parameter {0} was invalid: {1}", parameterName, message));
        }
    }
}
